//
//  SAStatisticsBusinessVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/22.
//

#import "SAStatisticsBusinessVC.h"
#import "HDDatePickerView.h"
#import "SASummaryQueryAPI.h"
#import "SAStatisticsBusinessModel.h"
#import "SAStatisticsBusinessCell.h"
#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"
#import "BubbleTableView.h"
#import "SAStatisticsBusinessHeaderView.h"

@interface SAStatisticsBusinessVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topContentView;
@property (nonatomic, strong) UILabel *startLab;
@property (nonatomic, strong) UILabel *startDateLab;
@property (nonatomic, strong) UILabel *endLab;
@property (nonatomic, strong) UILabel *endDateLab;
@property (nonatomic, strong) UIImageView *iconImageV;
@property (nonatomic, strong) UIButton *startDateBtn;
@property (nonatomic, strong) UIButton *endDateBtn;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@property (nonatomic, strong) NSMutableArray<SAStatisticsBusinessModel *> *dataMarr;
@property (nonatomic, strong) SASummaryQueryAPI *summaryQueryAPI;
@property (nonatomic, strong) UILabel *allShopLab;
@property (nonatomic, strong) UIImageView *allowImageV2;

@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreModel *> *storeList;
@property (nonatomic, strong) BubbleTableView *storeBubbleView;
@property (nonatomic, assign) NSInteger storeRow;

@end

@implementation SAStatisticsBusinessVC

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.summaryQueryAPI == api) {
        self.dataMarr = [NSMutableArray array];
        SAStatisticsBusinessModel *model = [SAStatisticsBusinessModel mj_objectWithKeyValues:data[@"data"][@"saleStatisticsDAO"]];
        model.titleName = @"销售";
        model.icon = @"SA_icon_sale";
        if (model.count.length == 0) {
            model.count = [NSString stringWithFormat:@"实销数 %@",@"0"];
        }else {
            model.count = [NSString stringWithFormat:@"实销数 %@",model.count];
        }
        if (model.price.length == 0) {
            model.price = [NSString stringWithFormat:@"实销额 %@",@"0.00"];
        }else {
            model.price = [NSString stringWithFormat:@"实销额 %0.2lf",[model.price doubleValue]/100.f];
        }
        [self.dataMarr addObject:model];
        
        
        SAStatisticsBusinessModel *model2 = [SAStatisticsBusinessModel mj_objectWithKeyValues:data[@"data"][@"returnStatisticsDAO"]];
        model2.titleName = @"退货";
        model2.icon = @"SA_icon_return";
        if (model2.count.length == 0) {
            model2.count = [NSString stringWithFormat:@"退货数 %@",@"0"];
        }else {
            model2.count = [NSString stringWithFormat:@"退货数 %@",model2.count];
        }
        if (model2.price.length == 0) {
            model2.price = [NSString stringWithFormat:@"退货额 %@",@"0.00"];
        }else {
            model2.price = [NSString stringWithFormat:@"退货额 %0.2lf",[model2.price doubleValue]/100.f];
        }
        [self.dataMarr addObject:model2];
        
        SAStatisticsBusinessModel *model3 = [SAStatisticsBusinessModel mj_objectWithKeyValues:data[@"data"][@"rechargeStatisticsDAO"]];
        model3.titleName = @"充值";
        model3.icon = @"SA_icon_topUp";
        if (model3.count.length == 0) {
            model3.count = [NSString stringWithFormat:@"充值数 %@",@"0"];
        }else {
            model3.count = [NSString stringWithFormat:@"充值数 %@",model3.count];
        }
        if (model3.price.length == 0) {
            model3.price = [NSString stringWithFormat:@"充值额 %@",@"0.00"];
        }else {
            model3.price = [NSString stringWithFormat:@"充值额 %0.2lf",[model3.price doubleValue]/100.f];
        }
        [self.dataMarr addObject:model3];
        
        SAStatisticsBusinessModel *model4 = [SAStatisticsBusinessModel mj_objectWithKeyValues:data[@"data"][@"dispatchStatisticsDAO"]];
        model4.titleName = @"调配入库";
        model4.icon = @"SA_putStorage";
        
        model4.enterCount = [NSString stringWithFormat:@"配入数 %@",model4.distributionInNum];
        model4.enterPrice = [NSString stringWithFormat:@"配入额 %0.2lf",[model4.distributionInAmount doubleValue]/100.f];
        
        model4.outCount = [NSString stringWithFormat:@"调入数 %@",model4.transferInNum];
        model4.outPrice = [NSString stringWithFormat:@"调入额 %0.2lf",[model4.transferInAmount doubleValue]/100.f];

        [self.dataMarr addObject:model4];
        
        SAStatisticsBusinessModel *model5 = [SAStatisticsBusinessModel mj_objectWithKeyValues:data[@"data"][@"dispatchStatisticsDAO"]];
        model5.titleName = @"调配出库";
        model5.icon = @"SA_pullStorage";
        
        model5.enterCount = [NSString stringWithFormat:@"配出数 %@",model5.distributionOutNum];
        model5.enterPrice = [NSString stringWithFormat:@"配出额 %0.2lf",[model5.distributionOutAmount doubleValue]/100.f];
        
        model5.outCount = [NSString stringWithFormat:@"调出数 %@",model5.transferOutNum];
        model5.outPrice = [NSString stringWithFormat:@"调出额 %0.2lf",[model5.transferOutAmount doubleValue]/100.f];
        
        [self.dataMarr addObject:model5];
        
        [self.tableView reloadData];
    }else if (self.systemStoreStoreListAPI == api) {
        self.storeList = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        for (NSInteger i = 0; i < self.storeList.count; i++) {
            if ([SAValueManger shareInStance].userInfo.merchantId == self.storeList[i].merchantId) {
                self.storeRow = i;
            }
        }
        [self showStoreList];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {

}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataMarr[section].isSelect == YES) {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAStatisticsBusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAStatisticsBusinessCell" forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(64);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SAStatisticsBusinessHeaderView *headerView = [[SAStatisticsBusinessHeaderView alloc] initWithReuseIdentifier:@"SAStatisticsBusinessHeaderView"];
    SAStatisticsBusinessModel *model = self.dataMarr[section];
    headerView.model = model;
    headerView.selectBlock = ^{
        model.isSelect = !model.isSelect;
        [tableView reloadData];
    };
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(64);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark - event
- (void)clickStartDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.startDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.endDateLab.text];
        if ([date1 compare:date2] == NSOrderedDescending) {
            [Prompt popPromptViewWithMsg:@"开始日期不能大于截止日期" duration:2];
        }else {
            weakSelf.startDateLab.text = selectedDate;
            weakSelf.summaryQueryAPI.startTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

- (void)clickEndDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.endDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.startDateLab.text];
        if ([date1 compare:date2] == NSOrderedAscending) {
            [Prompt popPromptViewWithMsg:@"截止日期不能小于开始日期" duration:2];
        }else {
            weakSelf.endDateLab.text = selectedDate;
            weakSelf.summaryQueryAPI.endTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

-(void)loadData {
    [self.summaryQueryAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedAllowBtn2 {
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *crossStoreSummary = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"crossStoreSummary"]];
    if ([crossStoreSummary isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有跨店查统计权限,请联系店长添加" duration:2];
        return;
    }
    
    if (self.storeList.count > 0) {
        [self showStoreList];
    }else {
        self.systemStoreStoreListAPI.returnAll = @"true";
        [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}
    
-(void)showStoreList{
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreModel *model in self.storeList) {
        if (model.storeName.length == 0) {
            model.storeName = @"";
        }
        [marr addObject:model.storeName];
    }
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.storeBubbleView) {
        self.storeBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.storeRow = row;
            self.summaryQueryAPI.merchantId = @(self.storeList[row].merchantId).stringValue;
            self.allShopLab.text = rowString;
            [self loadData];
        } hideBlock:^{
            self.storeBubbleView = nil;
        }];
        [self.storeBubbleView showWithTargetView:self.allowImageV2 maskSuperView:window];
        [self.storeBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.storeBubbleView.bubbleCellHeight = 50;
        self.storeBubbleView.selectRow = self.storeRow;
        self.storeBubbleView.isBubbleScrollEnabled = YES;
        self.storeBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"经营概括"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    [self.view addSubview:self.topContentView];
    [self.topContentView addSubview:self.startLab];
    [self.topContentView addSubview:self.startDateLab];
    [self.topContentView addSubview:self.endLab];
    [self.topContentView addSubview:self.endDateLab];
    [self.topContentView addSubview:self.iconImageV];
    [self.topContentView addSubview:self.startDateBtn];
    [self.topContentView addSubview:self.endDateBtn];
    [self.view addSubview:self.tableView];
    
    [self.topContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(StatusHeight));
        make.height.mas_equalTo(kScaleNum(44));
        make.right.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(0));
    }];
    
    [self.iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(29, 29));
    }];
    
    [self.startLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.iconImageV.mas_left).offset(kScaleNum(-68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.endDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.iconImageV.mas_right).offset(kScaleNum(68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.startDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    [self.endDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.endDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    UIView *grayView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 44, kBaseScreenWidth, 35)];
    grayView.backgroundColor = kTextBgColor;
    [self.view addSubview:grayView];
    
    UILabel *allShopLab = [[UILabel alloc] init];
    allShopLab.text = [SAValueManger shareInStance].userInfo.storeName;
    allShopLab.font = kBFont(15);
    allShopLab.textColor = kBlackColor;
    [grayView addSubview:allShopLab];
    self.allShopLab = allShopLab;
    
    UIImageView *allowImageV2 = [[UIImageView alloc] init];
    allowImageV2.image = [UIImage imageNamed:@"bule_downAllow"];
    [grayView addSubview:allowImageV2];
    allowImageV2.contentMode = UIViewContentModeCenter;
    self.allowImageV2 = allowImageV2;
    
    UIButton *allowBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [allowBtn2 addTarget:self action:@selector(clickedAllowBtn2) forControlEvents:UIControlEventTouchUpInside];
    [grayView addSubview:allowBtn2];
    
    [allShopLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(25));
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_lessThanOrEqualTo(kScaleNum(150));
        make.width.mas_greaterThanOrEqualTo(kScaleNum(50));
    }];
    
    [allowImageV2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_equalTo(kScaleNum(55));
        make.left.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(-10));
    }];
    
    [allowBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.right.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(30));
    }];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    _startDateLab.text = timeFormatStr;
    _endDateLab.text = timeFormatStr;
    
//    UIButton *showMoneyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [showMoneyBtn setImage:[UIImage imageNamed:@"SA_arrow_down"] forState:UIControlStateNormal];
//    [showMoneyBtn setImage:[UIImage imageNamed:@"SA_arrow_up"] forState:UIControlStateSelected];
//    showMoneyBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(48));
//    showMoneyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    showMoneyBtn.imageEdgeInsets = kEdgeInsetsMake(0, 0, 0, 15);
//    [showMoneyBtn addTarget:self action:@selector(clickedBhowMoneyBtn:) forControlEvents:UIControlEventTouchUpInside];
//    [whiteView addSubview:showMoneyBtn];
    
    self.summaryQueryAPI.startTime = timeFormatStr;
    self.summaryQueryAPI.endTime = timeFormatStr;
    self.summaryQueryAPI.merchantId = @([SAValueManger shareInStance].userInfo.merchantId).stringValue;
    [self loadData];
}

#pragma mark - lazy
- (UIView *)topContentView {
    if (!_topContentView) {
        _topContentView = [[UIView alloc] init];
        _topContentView.backgroundColor = [UIColor whiteColor];
    }
    return _topContentView;
}

- (UILabel *)startLab {
    if (!_startLab) {
        _startLab = [[UILabel alloc] init];
        _startLab.textColor = kBlackColor;
        _startLab.font = kFont(15);
        _startLab.text = @"开始";
    }
    return _startLab;
}

- (UILabel *)startDateLab {
    if (!_startDateLab) {
        _startDateLab = [[UILabel alloc] init];
        _startDateLab.textColor = kBlackColor;
        _startDateLab.font = kFont(15);
    }
    return _startDateLab;
}

- (UILabel *)endLab {
    if (!_endLab) {
        _endLab = [[UILabel alloc] init];
        _endLab.textColor = kBlackColor;
        _endLab.font = kFont(15);
        _endLab.text = @"截止";
    }
    return _endLab;
}

- (UILabel *)endDateLab {
    if (!_endDateLab) {
        _endDateLab = [[UILabel alloc] init];
        _endDateLab.textColor = kBlackColor;
        _endDateLab.font = kFont(15);
    }
    return _endDateLab;
}

- (UIImageView *)iconImageV {
    if (!_iconImageV) {
        _iconImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SA_to"]];
    }
    return _iconImageV;
}

- (UIButton *)startDateBtn {
    if (!_startDateBtn) {
        _startDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_startDateBtn addTarget:self action:@selector(clickStartDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startDateBtn;
}

- (UIButton *)endDateBtn {
    if (!_endDateBtn) {
        _endDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endDateBtn addTarget:self action:@selector(clickEndDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endDateBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 79), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 50)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAStatisticsBusinessCell class] forCellReuseIdentifier:@"SAStatisticsBusinessCell"];
    }
    return _tableView;
}

-(NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

-(SASummaryQueryAPI *)summaryQueryAPI {
    if (!_summaryQueryAPI) {
        _summaryQueryAPI = [SASummaryQueryAPI apiWithDelegate:self];
    }
    return _summaryQueryAPI;
}

-(NSMutableArray<SAStatisticsBusinessModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

-(NSMutableArray<SAStoreModel *> *)storeList {
    if (!_storeList) {
        _storeList = [NSMutableArray array];
    }
    return _storeList;
}


@end
